import { Router } from 'vue-router'
// import router from '@/router'
import { getToken } from '@/utils/auth'
import { clientSetting } from '@/config/client-setting'
import store from '@/store'
import baseConfig from '@/config'
import { initUserAuthAndMenu, isLoginBack, useLogoutUrl } from '@/utils/oneAccess-options'

const isOneAccess = clientSetting.oneAccessLogin
const isKeycloak = clientSetting.keycloakLogin
const clientId = baseConfig.clientId

// router.beforeEach((to: any, from: any) => {
//   const menu = store.getters['menu/getMenuList']
//   if (to.meta.requiresAuth) {
//     if ((!getToken() && !isKeycloak) || (menu.length === 0 && !isKeycloak)) {
//       return { path: '/login' }
//     }
//   } else if (to.path === '/404' && from.path === '/') {
//     // 解决keycloak登录/刷新重定向参数格式不对临时处理
//     const tpPath = to.redirectedFrom?.path
//     if (tpPath) {
//       return { path: tpPath.split('&')[0] }
//     }
//     return { path: '/' }
//   }
// })

const usePermission = (router: Router) => {
  router.beforeEach(async (to, from) => {
    console.log("from.fullPath:", from.fullPath)
    // 清空查询条件的缓存
    if (
      !from.fullPath.includes('/construction/detail') &&
      !from.fullPath.includes('/construction/edit') &&
      !from.fullPath.includes('/construction/add') &&
      !from.fullPath.includes('/construction/project-application') &&
      !from.fullPath.includes('/construction/project-review')
    ) {
      localStorage.removeItem(`projectList添加`)
      localStorage.removeItem(`projectList审核`)
    }
    const sysFlag = store.getters['menu/getSystemFlag']
    if (window.__MICRO_APP_ENVIRONMENT__ && sysFlag !== clientId) {
      // 当作为微应用时加载菜单（作为顶部菜单子应用启用下一行代码）
      // await store.dispatch('menu/getMenu')
    }
    if (isLoginBack(window.location.href) && isOneAccess) {
      await initUserAuthAndMenu()
    }
    const menu = store.getters['menu/getMenuList']
    if (to.meta.requiresAuth) {
      if ((!getToken() && !isKeycloak) || (menu.length === 0 && !isKeycloak)) {
        await useLogoutUrl()
      }
    } else if (to.path === '/404' && from.path === '/') {
      // 解决keycloak登录/刷新重定向参数格式不对
      const tpPath = to.redirectedFrom?.path
      if (tpPath) {
        return { path: tpPath.split('&')[0] }
      }
      return { path: '/' }
    }
    if (to.query.metaTitle) {
      to.meta.title = to.query.metaTitle
    }
  })
}

export default usePermission

